package com.timing.finder.framework;

import java.util.List;

/**
 * @author JingGe(* ^ ▽ ^ *)
 * @date 2023-03-06 16:16
 * @email 1158055613@qq.com
 */
public class DefaultTimeSeriesDataHandler<T extends TimeSeriesData> extends TimeSeriesDataHandler<T> {
    private final TimingFinderConfig config;
    private final CacheRepository cacheRepository;

    public DefaultTimeSeriesDataHandler(TimingFinderConfig config) {
        this.config = config;
        ProtoStuffSerializerAndDeserializer codec = new ProtoStuffSerializerAndDeserializer();
        cacheRepository = new RedisRepository(codec, codec, config);
    }

    public DefaultTimeSeriesDataHandler(TimingFinderConfig config, CacheRepository cacheRepository) {
        this.config = config;
        this.cacheRepository = cacheRepository;
    }

    @Override
    public String getKey(List<T> data) {
        if (data == null || data.size() == 0) {
            return null;
        }
        return data
                .get(0)
                .key();
    }

    @Override
    public long startOffset() {
        return config.defaultStartOffset;
    }

    @Override
    public long unitOffset() {
        return config.defaultUnitOffset;
    }

    @Override
    public long offsetIndex(T data) {
        long time = data.timestamp();
        if (time == 0) {
            return -1;
        }
        return ((time - startOffset()) / unitOffset()) + 1;
    }

    @Override
    public long initialSize() {
        return config.initialSize;
    }

    @Override
    public CacheRepository cacheRepository() {
        return cacheRepository;
    }

    @Override
    public long expiringTime() {
        return config.expiringTime * 24 * 60 * 60;
    }
}
